//
//  KINGEmoticon.swift
//  表情键盘
//
//  Created by king on 15/8/7.
//  Copyright © 2015年 king. All rights reserved.
//

import UIKit

class KINGEmoticonPackage: NSObject, CustomDebugStringConvertible {
    /// 表情包的名字
    var id: String
    var groupName:String = ""
    var emoticons:[KINGEmoticon]?
    
    init(id: String, groupName:String = "") {
        self.id = id
        self.groupName = groupName
    }
    //对外只提供一个类属性，用来加载所有的表情包，而且用static修饰，不会被多次加载
    static let packages = KINGEmoticonPackage.loadPackages()
    
    class func addFavouriteEmoticon(emoticon:KINGEmoticon) {
        //获取常用表情
        var ems = packages[0].emoticons!
        //删除最后的删除按钮，不让其参与排序
        ems.removeLast()
        //表情使用次数增加
        emoticon.times++
        //添加表情,如果上面不强制解包的话，这里需要进行强制解包
        let emoticons = ems.contains(emoticon)
        if !emoticons {
            ems.append(emoticon)
        }
        //对表情进行排序
        ems = ems.sort({ (e1, e2) -> Bool in
            return e1.times > e2.times
        })
        if !emoticons {
            ems.removeLast()
        }
        //排序之后，将按钮重新追加回来
        ems.append(KINGEmoticon(remove: true))
        //重新设置常用表情包
        packages[0].emoticons = ems
        print(ems.count)
    }
    
    private class func loadPackages() -> [KINGEmoticonPackage] {
        let path = bundlePath.stringByAppendingPathComponent("emoticons.plist")
        let dict:NSDictionary = NSDictionary(contentsOfFile: path)!
        let array = dict["packages"] as! [[String: AnyObject]]
        var arrM = [KINGEmoticonPackage]()
        //添加常用分组
        let package = KINGEmoticonPackage(id: "", groupName:"常用").appendEmptyEmotions()
        arrM.append(package)
        
        for d in array {
            let id = d["id"] as! String
            let package = KINGEmoticonPackage(id: id).loadEmoticons().appendEmptyEmotions()
            arrM.append(package)
        }
        //print(arrM)
        
        return arrM
    }
    //链式相应,加载表情包种的数据
    private func loadEmoticons() -> Self {
        let path = KINGEmoticonPackage.bundlePath.stringByAppendingPathComponent(id).stringByAppendingPathComponent("info.plist")
        let dict = NSDictionary(contentsOfFile: path)!
        groupName = dict["group_name_cn"] as! String
        let array = dict["emoticons"] as! [[String: AnyObject]]
        var arrM = [KINGEmoticon]()
        var index = 0
        for d in array {
            if index == 20 {
                arrM.append(KINGEmoticon(remove: true))
                index = 0
            }
            arrM.append(KINGEmoticon(id: id, dict: d))
            index++
        }
        emoticons = arrM
        return self
    }
    
    private func appendEmptyEmotions() -> Self {
        if emoticons == nil {
            emoticons = [KINGEmoticon]()
        }
        //判断是否整页 
        let count = emoticons!.count % 21
        
        //cout大于零有两种情况1、数组个数正好整除21 2、数组个数为零，如果数组个数为0 添加一个空页
        if count > 0 || emoticons?.count == 0 {
            for _ in count..<20 {
                emoticons?.append(KINGEmoticon(remove: false))
            }
        }
        emoticons?.append(KINGEmoticon(remove: true))
        return self
    }
    /// bundle目录
    static let bundlePath = NSBundle.mainBundle().bundlePath.stringByAppendingPathComponent("Emoticons.bundle")
    
    override var description: String {
        return "\(id) \(emoticons)"
    }
}

class KINGEmoticon: NSObject {
    /// 表情的点击次数，根据这个字段做常用表情的排序
    var times:Int = 0
    ///表情目录
    var id: String?
    /// 发给服务器的表情文字
    var chs: String?
    /// 本地显示的图片文件夹
    var png: String?
    var imagePath:String {
        if chs == nil {
            return ""
        }
        return KINGEmoticonPackage.bundlePath.stringByAppendingPathComponent(id!).stringByAppendingPathComponent(png!)
    }
    /// emoji的代码
    var code: String? {
        didSet{
            //创建一个扫描器
            let scanner = NSScanner(string: code!)
            //读取一个整数
            var value: UInt32 = 0
            scanner.scanHexInt(&value)
            //将证书转换为字符串
            emoji = String(Character(UnicodeScalar(value)))
        }
    }
    var emoji: String?
    init(id:String, dict:[String:AnyObject]) {
        //要在调用父类之前，将自己的成员变量赋值
        self.id = id
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    //标记是否是删除按钮，true表示是删除按钮，false表示是空白表情
    var removeEmoticon = false
    init(remove:Bool) {
        removeEmoticon = remove
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {    }
    override var description: String {
        return "\(id) \(chs) \(png) \(code))"
    }
}
